package com.eliteams.quick4j.app.service.impl;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.eliteams.quick4j.app.dao.SitemaprsslistMapper;
import com.eliteams.quick4j.app.model.Sitemaprsslist;
import com.eliteams.quick4j.app.model.SitemaprsslistExample;
import com.eliteams.quick4j.app.service.SitemaprssListService;
import com.eliteams.quick4j.core.entity.SiteMapUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Created by Administrator on 2017/11/15.
 */
@Service
public class SitemaprssListServiceImpl implements SitemaprssListService {

	private static Log logger1 = LogFactory.getLog("mylogger1");

	@Resource
	private SitemaprsslistMapper sitemaprsslistMapper;

	@Override
	public int countByExample(SitemaprsslistExample example) {
		return sitemaprsslistMapper.countByExample(example);
	}

	@Override
	public int deleteByExample(SitemaprsslistExample example) {
		return sitemaprsslistMapper.deleteByExample(example);
	}

	@Override
	public int deleteByPrimaryKey(Integer id) {
		return sitemaprsslistMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(Sitemaprsslist record) {
		return sitemaprsslistMapper.insert(record);
	}

	@Override
	public int insertSelective(Sitemaprsslist record) {
		return sitemaprsslistMapper.insertSelective(record);
	}

	@Override
	public List<Sitemaprsslist> selectByExample(SitemaprsslistExample example) {
		return sitemaprsslistMapper.selectByExample(example);
	}

	@Override
	public Sitemaprsslist selectByPrimaryKey(Integer id) {
		return sitemaprsslistMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByExampleSelective(Sitemaprsslist record, SitemaprsslistExample example) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updateByExample(Sitemaprsslist record, SitemaprsslistExample example) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updateByPrimaryKeySelective(Sitemaprsslist record) {
		return sitemaprsslistMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKey(Sitemaprsslist record) {
		return sitemaprsslistMapper.updateByPrimaryKey(record);
	}

	/**
	 * 获取循环一次的SiteMap数据
	 */
	@Override
	public List<String> selectSiteMap1(String uuId) {
		List<String> htmlList = new ArrayList<>();// 存放url
		List<Sitemaprsslist> list1 = sitemaprsslistMapper.selectSiteMap1();
		if(!list1.isEmpty()){
			for (Sitemaprsslist sitemap : list1) {
				String url = sitemap.getUrl();
				logger1.info(" "+uuId+" "+url+" start");
				if (!url.isEmpty()) {
					URL url2;
					SAXReader reader = new SAXReader();
					Document document;
					Element rootElement = null;
					Element fooElement;
					try {
						url2 = new URL(url);
						document = reader.read(url2);
						rootElement = document.getRootElement();
						for (Iterator i = rootElement.elementIterator("url"); i.hasNext();) {
							fooElement = (Element) i.next();
							String strXML = fooElement.elementText("loc");
							if (!strXML.isEmpty()) {
								htmlList.add(strXML);
							}
						}
					} catch (MalformedURLException e1) {
						logger1.info(" "+uuId+" " + e1);
					}catch (DocumentException e1) {
						logger1.info(" "+uuId+" " + e1);
					}
					logger1.info(" "+uuId+" "+url+" success");
				}
			}
		}
		return htmlList;
	}

	/**
	 * 获取循环两次的SiteMap数据
	 */
	@Override
	public List<String> selectSiteMap2() {
		List<String> htmlList = new ArrayList<>();// 存放url
		List<Sitemaprsslist> list2 = sitemaprsslistMapper.selectSiteMap2();
		for (Sitemaprsslist sitemap : list2) {
			String url_ = sitemap.getUrl();
			if (!url_.isEmpty()) {
				try {
					//SiteMapUtils.getXMLs(url_,uuId);
					//遍历文件
					String u="E:/testsitemap/";
					SAXReader reader1 = new SAXReader(); 
					File file = new File(u);
					File[] files = null;
					if (file.exists()) {
			            files = file.listFiles();
			            for (File file2 : files) {
			                if (file2.isDirectory()) {
			                	logger1.info("文件夹:" + file2.getAbsolutePath());
			                } else {
			                	logger1.info("文件:" + file2.getAbsolutePath());//获取每个文件路径
			                    //读取文件 转换成Document  
			        	        Document document = reader1.read(new File(file2.getAbsolutePath())); 
			        	        Element rootElement=document.getRootElement();
			        			Element fooElement;
			        			for(Iterator i=rootElement.elementIterator("url");i.hasNext();){
			        				fooElement=(Element)i.next();
			        				String htmls_=fooElement.elementText("loc");
			        				logger1.info("URL："+htmls_);
			        				htmlList.add(htmls_);
			        			}
			                }
			            }
			            
			        } else {
			        	logger1.info("文件不存在!");
			        }
					logger1.info("html个数为："+htmlList.size());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return htmlList;
	}

	/**
	 * 获取RSS数据
	 */
	@Override
	public List<Sitemaprsslist> selectRSS() {
		return sitemaprsslistMapper.selectRSS();

	}

	@Override
	public List<Sitemaprsslist> selectSiteMap() {
		
		return sitemaprsslistMapper.selectSiteMap2();
	}
	
	@Override
	// 分页查询会员
	public List<Sitemaprsslist> selectSiteList(@Param("start") int start, @Param("size") int size) {
		return sitemaprsslistMapper.selectSiteList(start, size);
	}

	@Override
	// 查数据总数
	public int selectCountMember() {
		return sitemaprsslistMapper.selectCountMember();
	}

	// 封装返回数据分页json
	@Override
	public void fomartReturnJsonSiteView(HttpServletRequest req, HttpServletResponse resp, int start, int size) {
		JSONArray jsonArray = new JSONArray();
		JSONObject jo = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Sitemaprsslist> list = sitemaprsslistMapper.selectSiteList(start, size);
		int fansCount = sitemaprsslistMapper.selectCountMember();
		int pages = 0;
		if (fansCount % size != 0) {
			pages = fansCount / size + 1;
		} else {
			pages = fansCount / size;
		}

		for (Sitemaprsslist s : list) {
			jo = new JSONObject();
			jo.put("id", s.getId());
			jo.put("name", s.getName());
			jo.put("url", s.getUrl());
			jo.put("type", s.getType());
			jo.put("pages", pages);
			jsonArray.add(jo);
		}
		try {
			// 后台输出测试
			System.out.println(jsonArray.toString());
			// 设置字符集
			req.setCharacterEncoding("UTF-8");
			// 页面输出
			resp.getWriter().write(jsonArray.toString());
			resp.getWriter().flush();
			resp.getWriter().close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	//通过id修改当前数据
	public int updateSiteById(Sitemaprsslist sitemaprsslist){
		return sitemaprsslistMapper.updateSiteById(sitemaprsslist);
	}
}
